package com.icez.base_util_library

import android.annotation.SuppressLint
import android.app.Activity
import android.content.ContentUris
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.icez.base_util_library.model.SystemImgModel
import java.io.File

/**
 *  文件工具类
 * 权限需要添加
 * <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 * application节点添加
 * android:requestLegacyExternalStorage="true"
 */
class FileUtil {
    companion object {
        val instance: FileUtil by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            FileUtil()
        }
    }

    public fun getSDFile(): File? {
        return Environment.getExternalStorageDirectory()
    }

    /**
     *  创建文件
     */
    public fun createFile(pathFileDir: String, pathFileName: String): File {
        val storageDir = File(getSDFile(), pathFileDir)
        if (!storageDir.exists()) {
            storageDir.mkdirs()
        }
        val file = File(storageDir, pathFileName)
        if (!file.exists()) {
            file.createNewFile()
        }
        return file
    }

    /**
     *  创建目录
     */
    public fun createDir() {

    }

    /**
     *  是否存在指定的文件
     */
    public fun isExitFile() {

    }

    /**
     *  是否存在指定的目录
     */
    public fun isExitDir() {

    }


    /**
     *  获取指定路径的所有图片
     * @param relativeDir 先对路径文件地址
     * @param imgLists 所有的图片
     */
    public fun getAllImgForDir(
        relativeDir: String,
        imgLists: ArrayList<SystemImgModel>?
    ): ArrayList<SystemImgModel> {
        val dirImgLists = ArrayList<SystemImgModel>()
        imgLists?.forEachIndexed { index, systemImgModel ->
            if (systemImgModel.rellativePath.equals(relativeDir)) {
                dirImgLists.add(systemImgModel)
            }
        }
        return dirImgLists
    }

    /**
     *  获取所有图片的路径
     */
    public fun getAllImgDir(imgLists: ArrayList<SystemImgModel>?): ArrayList<String> {
        val dirLists = ArrayList<String>()
        imgLists?.forEachIndexed { index, systemImgModel ->
            if (dirLists.isNullOrEmpty()) {
                dirLists.add(systemImgModel.rellativePath ?: "")
            } else {
                if (!dirLists.contains(systemImgModel.rellativePath)) {
                    dirLists.add(systemImgModel.rellativePath ?: "")
                }
            }
        }
        return dirLists
    }


    /**
     *  获取所有的图片
     * @param activity Activity
     * @param maxSizeM 过滤图片的最大M数
     * @param mUri 图片uri
     */
    public suspend fun getAllImg(fragment: Fragment?,
                                 maxSizeM: Float = 0f,
                                 mContentUri: Uri? = null,
                                 mFilePath:String ?= null): ArrayList<SystemImgModel> {
        return getAllImg(fragment?.requireActivity() as AppCompatActivity,maxSizeM,mContentUri,mFilePath)
    }


    /**
     *  获取所有的图片
     * @param activity Activity
     * @param maxSizeM 过滤图片的最大M数
     * @param mUri 图片uri
     */
    @SuppressLint("Range")
    public suspend fun getAllImg(
        activity: AppCompatActivity?,
        maxSizeM: Float = 0f,
        mContentUri: Uri? = null,
        mFilePath:String ?= null
    ): ArrayList<SystemImgModel> {
        val uri = if (mContentUri == null) {
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        } else {
            mContentUri
        }

        val imgsList = ArrayList<SystemImgModel>()
        val projImage = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            arrayOf(
                MediaStore.Images.Media._ID,
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.SIZE,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_MODIFIED,
                MediaStore.Images.Media.RELATIVE_PATH
            )
        } else {
            arrayOf(
                MediaStore.Images.Media._ID,
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.SIZE,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_MODIFIED
            )
        }
        var selection:String ?= null
        var selectionArgs:Array<String> ?= null
        if(mFilePath.isNullOrEmpty()){
            selection = null
            selectionArgs = null
        }else{
            selection = MediaStore.Images.Media.DATA + "=?"
            selectionArgs = arrayOf(mFilePath)
        }
        activity?.contentResolver?.query(
            uri,
            projImage,
            selection,
            selectionArgs,
            MediaStore.Images.Media.DATE_MODIFIED + " desc"
        )?.use {
            while (it.moveToNext()) {
                var mSystemImgModel: SystemImgModel? = null
                val id = it.getColumnIndex(MediaStore.Images.Media._ID)
                val size = it.getInt(it.getColumnIndex(MediaStore.Images.Media.SIZE))
                val absPath = it.getString(it.getColumnIndex(MediaStore.Images.Media.DATA)) ?: ""
                val relativePath = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    it.getString(it.getColumnIndex(MediaStore.Images.Media.RELATIVE_PATH)) ?: ""
                } else {
                    absPath.replace(getSDFile()?.absolutePath ?: "", "").substringBeforeLast("/")
                }
                if (maxSizeM == 0f) {
                    mSystemImgModel = SystemImgModel(
                        it.getLong(id).toString() ?: "",
                        it.getString(it.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)) ?: "",
                        size.toString() ?: "",
                        relativePath.trim('/'.toChar()),
                        it.getString(it.getColumnIndex(MediaStore.Images.Media.DATA)) ?: "",
                        ContentUris.withAppendedId(uri, it.getLong(id)) ?: null
                    )
                    imgsList.add(mSystemImgModel)
                } else if ((size / 1024f) <= maxSizeM) {
                    mSystemImgModel = SystemImgModel(
                        it.getLong(id).toString() ?: "",
                        it.getString(it.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)) ?: "",
                        size.toString() ?: "",
                        relativePath.trim('/'.toChar()),
                        it.getString(it.getColumnIndex(MediaStore.Images.Media.DATA)) ?: "",
                        ContentUris.withAppendedId(uri, it.getLong(id)) ?: null
                    )
                    imgsList.add(mSystemImgModel)
                }


            }
        }
        return imgsList
    }


    public fun saveBitmap(activity: AppCompatActivity?,bitmap: Bitmap){

    }


}